package com.andy.common.db.repository

import androidx.lifecycle.LiveData
import com.andy.common.db.dao.UserDao
import com.andy.common.db.entity.UserEntity
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext

/**
 * Author:Andy
 * Date:2023/3/21 16:55
 * Description:UserRepository用于对用户表的操作
 */
class UserRepository private constructor(private val userDao: UserDao) {
    companion object {
        @Volatile
        private var instance: UserRepository? = null
        fun getInstance(userDao: UserDao): UserRepository = instance ?: synchronized(this) {
            instance ?: UserRepository(userDao).also {
                instance = it
            }
        }
    }

    suspend fun insertUser(user: UserEntity) {
        withContext(IO) {
            userDao.insertUser(user)
        }
    }

    suspend fun deleteUser(user: UserEntity) {
        withContext(IO) {
            userDao.deleteUser(user)
        }
    }

    suspend fun deleteUser(id: Long) {
        withContext(IO) {
            userDao.deleteUser(id)
        }
    }

    suspend fun deleteAll() {
        withContext(IO) {
            userDao.deleteAll()
        }
    }

    suspend fun updateUser(user: UserEntity) {
        withContext(IO) {
            userDao.updateUser(user)
        }
    }

    suspend fun updateUser(id: Long, name: String) {
        withContext(IO) {
            userDao.updateUser(id, name)
        }
    }

    fun getUser(id: Long): LiveData<UserEntity> = userDao.getUser(id)
    fun getAllUsers(): List<UserEntity> = userDao.getAllUsers()

}